<template>
  <div class="app-container">
      <div class="filter-container">
        <el-select clearable class="filter-item" v-model="selectedService" @change='handleSelService' style="width: 200px"  placeholder="请选择Service">
          <el-option v-for="s in  services" :key="s.name" :label="s.name" :value="s.name">
          </el-option>
        </el-select>
        <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate"  v-waves type="primary" icon="el-icon-edit">添加API</el-button>
      </div>

      <div class="table">
        <el-table  :data="apis" border fit highlight-current-row style="width: 100%;min-height:1000px;"  :default-sort = "{prop: 'update_date', order: 'descending'}">
          <el-table-column align="center" label="Name" width="250" prop="name" sortable>
            <template slot-scope="scope">
              <span>{{scope.row.name}}</span>
            </template>
          </el-table-column>
          <el-table-column width="100" align="center" label="代理类型" prop="route_type">
             <template slot-scope="scope">
                <span v-show="scope.row.route_type==1">同步代理</span>
                <span v-show="scope.row.route_type==2">重定向</span>
                <span v-show="scope.row.route_type==2">异步代理(特殊)</span>
            </template>
          </el-table-column>
          <el-table-column width="350" align="center" label="目标地址" prop="route_addr">
            <template slot-scope="scope">
              <span>{{scope.row.route_addr}}</span>
            </template>
          </el-table-column>
           <el-table-column width="200" align="center" label="更新日期" prop="update_date" sortable>
            <template slot-scope="scope">
                <span>{{scope.row.update_date}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button  type="primary" size="mini" @click="handleEdit(scope.row)">管理</el-button>
              <el-button  type="info" size="mini" @click="handleTest(scope.row)">测试</el-button>
              <el-button  size="mini" type="danger" @click="delApi(scope.row.service,scope.row.name)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>


      <el-dialog :title="dialogTitle" :visible.sync="createApiVisible">
        <el-form :rules="createRules" ref="dataForm" :model="tempApi" label-position="left" label-width="70px" style='width: 550px; margin-left:50px;'>
          <el-form-item label="Name" prop="name">
            <el-input v-if="dialogStatus=='create'" v-model="tempApi.name" placeholder="例如a.b.v1,只支持英文字母、数字和.,一旦输入不可更改!" :disabled="dialogStatus=='edit'">
                <template  slot="prepend" >{{selectedService}} .</template>
            </el-input>
             <el-input v-else v-model="tempApi.name" placeholder="例如a.b.v1,只支持英文字母、数字和.,一旦输入不可更改!" :disabled="dialogStatus=='edit'">
            </el-input>
          </el-form-item>

          <el-form-item label="代理类型" prop="route_type">
            <el-select  class="filter-item" v-model="tempApi.route_type" style="width: 150px"  placeholder="请选择代理类型">
              <el-option label="同步代理" value="1"></el-option>
              <el-option  label="重定向" value="2"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="目标地址" prop="route_addr">
            <el-input  v-if="dialogStatus=='create'"  v-model="tempApi.route_addr" placeholder="输入目标网络地址">
                 <template slot="prepend" >Http://</template>
            </el-input>
            <el-input  v-else  v-model="tempApi.route_addr" placeholder="输入目标网络地址">
            </el-input>
          </el-form-item>

          <el-form-item label="超时设置" prop="req_timeout" style="width:200px">
            <el-input v-model="tempApi.req_timeout" placeholder="请求超时设置">
              <template slot="append">秒</template>
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="createApiVisible = false">取消</el-button>
          <el-button  type="primary" @click="createSubmit">
            <span v-if="dialogStatus=='create'">创建</span>
            <span v-else>提交</span>
          </el-button>
        </div>
      </el-dialog>


      <el-dialog title="测试API" :visible.sync="testApiVisible">
        <el-form :rules="createRules" ref="dataForm" :model="tempApi" label-position="left" label-width="70px" style='width: 550px; margin-left:50px;'>
          <el-form-item label="API名"  style="width:300px">
            <el-input v-model="testApi.name" placeholder="API名" disabled=true>
            </el-input>
          </el-form-item>

          <el-form-item label="目标地址"  style="width:300px">
            <el-input v-model="testApi.route_addr" placeholder="目标地址" disabled=true>
            </el-input>
          </el-form-item>
          
          <el-form-item label="Method">
            <el-select  class="filter-item" v-model="testMethod" style="width: 200px"  placeholder="选择HTTP Method">
              <el-option label="GET" value="GET"></el-option>
              <el-option  label="POST" value="POST"></el-option>
              <el-option  label="PUT" value="PUT"></el-option>
              <el-option  label="DELETE" value="DELETE"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="TFE地址" style="width:400px">
            <el-input v-model="tfeAddr" placeholder="TFE地址" disabled=true>
            </el-input>
          </el-form-item>


          <el-form-item label="请求参数">
            <el-input type="textarea" :autosize="{ minRows: 6, maxRows: 8}" placeholder="测试结果展示" :value="makeParam(testParams)" disabled="true">
            </el-input>
          </el-form-item>
          <el-form-item label="添加参数">
            <el-input  placeholder="新参数" style="width:150px" v-model="tempKey">
                <template slot="prepend">Key</template>
            </el-input>
            <el-input  placeholder="新参数" style="width:150px" v-model="tempVal">
                <template slot="prepend">Val</template>
            </el-input>
            <el-button @click="addParam" type="success" size="medium">添加</el-button>
            <el-button @click="clearParam" type="warning" size="medium">清空</el-button>
          </el-form-item>

          <el-form-item label="具体输出">
            <el-input type="textarea" :autosize="{ minRows: 6, maxRows: 8}" placeholder="测试结果展示" v-model="testResult" disabled="true">
            </el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="testApiVisible = false">取消</el-button>
          <el-button @click="startTest" type="primary">开始测试</el-button>
        </div>
      </el-dialog>
  </div>
</template>

<script>
/* eslint-disable */
import waves from '@/directive/waves' // 水波纹指令
import {proxy} from '@/api/apiProxy'
import request from '@/utils/request' 

export default {
  name: 'api',
  directives: {
    waves
  },
  data() {
      return {
        services:[
          {name: 'a'},
          {name: 'b'}
        ],
        selectedService: '',
        
        apis: [],

        tempApi: {
          route_type: '1',
          req_timeout: 30
        },

        createApiVisible: false,
        createRules: {
          name: [{ required: true, message: '请输入API Name,例如party.account.create', trigger: 'blur' }],
          route_addr: [{ required: true, message: '请输入目标地址', trigger: 'blur' }]
        },
        dialogStatus: 'create',
        dialogTitle: '创建API',

        testApiVisible: false,
        testResult: '',
        testApi: {},
        testMethod: 'GET',
        testPass : '',
        tfeAddr : '',
        testParams: {}, 
        tempKey:'',
        tempVal:''
      }
  },
  methods: {
    handleEdit(api) {
      this.dialogStatus = 'edit'
      this.dialogTitle = '编辑API'
      this.tempApi = api 
      this.createApiVisible = true
    },
    clearParam() {
      this.testParams = {}
      this.testParams.api_name=this.testApi.name
    },
    addParam() {
      this.testParams[this.tempKey] = this.tempVal
      this.tempKey = ''
      this.tempVal = ''
    },
    makeParam(p) {
      return JSON.stringify(p,null,'\t')
    },
    startTest() {
      this.testResult = ''
      this.testPass = ''
      request({
            url: '/tools/testApi',
            method: 'POST',
            params: {
                method: this.testMethod,
                tfe_addr: process.env.TFE_ADDR,
                params: this.testParams,
            }
        }).then(response => {
          if (response.data.status == 200) {
              this.$message({
                message: '测试成功',
                type: 'success',
                duration: 5 * 1000,
                center: true
              })
              this.testResult = response.data.data
              this.testPass = 'true'
          } else {
            this.$message({
                message: '测试失败,http code:'+ response.data.status,
                type: 'warning',
                duration: 5 * 1000,
                center: true
              })
             this.testResult = response.data.message
             this.testPass = 'false'
          }
            
        }).catch(error => {
        })
    },
    handleTest(api) {
      this.testApi = api 
      this.testResult = ''
      this.testApiVisible = true
      this.testPass = ''
      this.tfeAddr = process.env.TFE_ADDR
      this.testParams.api_name=api.name
    },
    delApi(service,name) {
        this.$confirm('此操作将永久删除<strong>该API</strong>, 是否继续删除?', '提示', {
          dangerouslyUseHTMLString: true,
          cancelButtonText: '不，赶紧取消删除',
          confirmButtonText: 'ok',
          type: 'error'
        }).then(() => {
            var params = {
                target_service: 'tfe.manage',
                target_path: '/manage/api/delete',
                service: service,
                name: name
            }
          proxy('POST',params).then(res => {
            if (res.data.status != 200) {
               this.$message({
                  message: res.data.message,
                  type: 'warning',
                  duration: 3 * 1000,
                  center: true
                })
                return 
            }
            this.loadApis()
            this.$message({
                message: '删除API成功',
                type: 'success',
                duration: 3 * 1000,
                center: true
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    createSubmit() {
      if (this.tempApi.name == '' || this.tempApi.route_addr == '') {
        this.$message({
              message: '必填参数不能为空',
              type: 'warning',
              duration: 3 * 1000,
              center: true
        })
        return 
      }

      if (this.dialogStatus == 'create') {
         var params = {
                target_service: 'tfe.manage',
                target_path: '/manage/api/create',
                service: this.selectedService,
                name: this.selectedService+'.'+this.tempApi.name,
                route_type: this.tempApi.route_type,
                route_addr: 'http://'+this.tempApi.route_addr,
                req_timeout: this.tempApi.req_timeout
        }
        proxy('POST',params).then(res => {
          this.createApiVisible = false 
           this.loadApis()
           this.$message({
                message: '创建API成功',
                type: 'success',
                duration: 3 * 1000,
                center: true
            })
        })
      } else {
        var params = {
                target_service: 'tfe.manage',
                target_path: '/manage/api/update',
                service: this.tempApi.service,
                name: this.tempApi.name,
                route_type: this.tempApi.route_type,
                route_addr: this.tempApi.route_addr,
                req_timeout: this.tempApi.req_timeout
        }
        proxy('POST',params).then(res => {
          this.createApiVisible = false 
           this.loadApis()
           this.$message({
                message: '编辑API成功',
                type: 'success',
                duration: 3 * 1000,
                center: true
            })
        })
      }
    },
    handleCreate() {
      if (this.selectedService=='') {
          this.$message({
              message: '请先选择Service',
              type: 'warning',
              duration: 3 * 1000,
              center: true
          })
          return 
      }
      this.tempApi = {
        name: '',
        route_addr:'',
        route_type:'1',
        req_timeout: 30
      }
      this.createApiVisible = true
      this.dialogStatus = 'create'
      this.dialogTitle = '创建API'
    },
    handleSelService() {
       this.loadApis()
    },
    loadApis() {
       // 加载Service底下的所有API
        var params = {
                target_service: 'tfe.manage',
                target_path: '/manage/api/query',
                service: this.selectedService,
            }
        proxy('POST',params).then(res => {
           this.apis = JSON.parse(res.data.data)
           console.log(this.apis)
        })
    },
    loadServices() {
      // 加载该用户的所有service
        var params = {
                target_service: 'tfe.manage',
                target_path: '/manage/service/query',
            }
        proxy('POST',params).then(res => {
           if (res.data.status == 200) {
             this.services = JSON.parse(res.data.data)
             if (this.services.length > 0) {
               this.selectedService = this.services[0].name
               this.loadApis()
             }
           }
        })
    }
  },
  created() {
    this.loadServices()
  },
  destroyed() {
    // window.removeEventListener('hashchange', this.afterQRScan)
  }
}
</script>
